// 引用用户请求api
import userApi from "@/api/user.js"
import {
	setToken
} from "../../utils/auth";

export default {
	namespaced: true,
	state: {
		userInfo: {},
	},
	// 异步操作
	actions: {
		// 调用方法 dispatch
		login({dispatch}) {
			return new Promise((resolve, reject) => {
				let p1 = dispatch("wxSilentLogin");
				// let p2 = dispatch("wxGetUserProfile");
				Promise.all([p1])
					.then((res) => {
						resolve(res);
					})
					.catch((error) => {
						console.log(error);
					});

			});
		},

		wxSilentLogin() {
			return new Promise((resolve, reject) => {
				// 获取用户信息
				const getUserInfo = function() {
					uni.getUserInfo({
						provider: 'weixin',
						success: function(infoRes) {
							userApi.login({
								code: uni.getStorageSync('sessionCode'),
								iv: infoRes.iv,
								encrypted_data: infoRes.encryptedData,
								type: 1,
								branch_uuid: "dd39f41b-61c2-472b-0a77-e7f273359c42"
							}).then(res => {
								setToken(res.data.token)
								resolve(true)
							})
						},
						fail: function(err) {
							conosle.log(err)
							reject(true)
						}
					});
				}
				// 查看是否获取过微信授权
				const getSetting = function() {
					const self = this
					uni.getSetting({
						success(res) {
							if (res.authSetting && res.authSetting['scope.userInfo']) {
								checkSession()
								return
							}
							// 申请获取用户授权
							uni.authorize({
								scope: 'scope.userInfo',
								success() {
									// 授权成功
									checkSession()
								},
								fail(e) {
									console.log(e)
									reject(true)
								}
							})
						}
					})
				}
				// 检测用户登陆状态是否过期
				const checkSession = function() {
					const self = this
					uni.checkSession({
						success(d) {
							console.log('未过期')
							console.log('sessionCode', uni.getStorageSync('sessionCode'))
							if (!uni.getStorageSync('sessionCode') || uni.getStorageSync(
									'sessionCode').length < 0) {
								login()
								return false
							}
							getUserInfo()
						},
						fail(e) {
							console.log('已经过期')
							console.log(e)
							login()
						}
					})
				}
				// 进行用户的wx 登陆
				const login = function() {
					const self = this
					uni.login({
						provider: 'weixin',
						success: function(loginRes) {
							// 本地缓存 code 
							uni.setStorageSync('sessionCode', loginRes.code)
							getUserInfo()
						},
						fail: function(err) {
							console.log(err)
							reject(true)
						}
					})
				}
				
				getSetting()
			});
		}
	},
	// 同步操作 调用方法 commit
	mutations: {
	    login(state, data) {
	    }
	},
};
